package com.aco.party.web.controller.system;

import com.aco.party.util.ImageUtils;
import com.aco.party.util.PathUtil;
import com.aco.party.util.WebModelUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.CharSet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;

import static com.aco.party.util.WebModelUtil.getImgPath;
/**
 * Created by WangShijun on 2016/3/9.
 */
@Controller
@RequestMapping("/system")
public class ImagesController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ImagesController.class);

    @RequestMapping("/getImg")
    public void getImg(HttpServletRequest request,HttpServletResponse response,@RequestParam(required = true)String imgId,Integer w,Integer h){
        ServletOutputStream out = null;
        try {
//            logger.info("系统编码" + System.getProperty("file.encoding"));
//            logger.info("queryString:" + request.getQueryString());
            out = response.getOutputStream();
//            logger.info("urlDecode:file.encoding" +URLDecoder.decode(imgId, System.getProperty("file.encoding")));
//            logger.info("urlDecode:gbk" +URLDecoder.decode(imgId, "gbk"));
//            logger.info("urlDecode:utf-8" +URLDecoder.decode(imgId, "utf-8"));
            File img = new File(getImgPath() + URLDecoder.decode(imgId, System.getProperty("file.encoding")));
            if(!img.exists()) {
                try {
                    if(imgId.contains("/")){
                        StringBuilder temp = new StringBuilder();
                        String[] imgIds = imgId.split("/");
                        for (int i =0; i<imgIds.length -1; i++){
                            temp.append(imgIds[i] + "/");
                        }
                        temp.append(URLEncoder.encode(imgIds[imgIds.length - 1], "utf-8"));
                        imgId = temp.toString();
                    }
                    logger.info("需要去wordpress获取图片 URL:" + WebModelUtil.get404ImgPath() + imgId);
                    URL url = new URL(WebModelUtil.get404ImgPath() + imgId);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5 * 1000);
                    InputStream inStream = conn.getInputStream();
                    byte[] data = readInputStream(inStream);
                    out.write(data);
                    inStream.close();
                    conn.disconnect();
                    return;
                }catch (Exception e){
                    logger.error(e.toString());
                    logger.error(e.getStackTrace().toString());
                    return;
                }finally {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                if (w != null) {
                    String fileSuffix = PathUtil.getExtension(img.getAbsolutePath());
                    String outPath = null;
                    File outPathCompress = null;
                    if(".gif".equals(fileSuffix)) {
                        outPath = img.getAbsolutePath();
                        logger.info("该图片是gif格式，不需要进行宽高缩放！");
                        outPathCompress = new File(outPath);
                    }else{
                        w = w * 2;
                        outPath = img.getAbsolutePath().substring(0, img.getAbsolutePath().lastIndexOf('.')) + "_" + w + fileSuffix;
//                    logger.info("outPath:" + outPath);
                        outPathCompress = new File(outPath);
                        if (!outPathCompress.exists()) {
                            try{
                                ImageUtils.compressImage(img.getAbsolutePath(), outPath, w);
                            }catch (Exception e){
                                logger.warn("压缩图片异常！使用非压缩图片！" + StringUtils.join(e.getStackTrace(),",\r\n"));
                                outPath = img.getAbsolutePath();
                            }
                            outPathCompress = new File(outPath);
                        }
                    }


                    byte[] data = FileUtils.readFileToByteArray(outPathCompress);
                    out.write(data);
                    imgId = outPath;
                    logger.info("本地存在图片，需要获取 imgId:" + imgId);
                } else {
                    byte[] data = FileUtils.readFileToByteArray(img);
                    out.write(data);
                }
            }
            response.setContentType("image/" + PathUtil.getExtension(imgId).replace(PathUtil.DOT,""));
        } catch (IOException e) {
            logger.error("错误：" + e);
            logger.error(StringUtils.join(e.getStackTrace()) + ",\r");
        }finally {
            if(out != null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

}
